package com.example.back.controller;

import com.example.back.service.DeepSeekService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.Map;
import java.util.HashMap;
import org.springframework.http.HttpStatus;
import java.util.Set;

@RestController
@RequestMapping("/api")
@CrossOrigin(origins = "http://localhost:5173", allowedHeaders = "*", methods = {
    RequestMethod.GET, RequestMethod.POST, RequestMethod.PUT,
    RequestMethod.DELETE, RequestMethod.OPTIONS
})
public class CodeGenerationController {

    private static final Logger logger = LoggerFactory.getLogger(CodeGenerationController.class);
    private final DeepSeekService deepSeekService;
    
    public CodeGenerationController(DeepSeekService deepSeekService) {
        this.deepSeekService = deepSeekService;
    }
    
    @PostMapping("/generate-code")
    public ResponseEntity<Map<String, String>> generateCode(@RequestBody Map<String, String> request) {
        logger.info("Received code generation request");
        String prompt = request.get("prompt");
        if (prompt == null || prompt.isEmpty()) {
            logger.warn("Received empty prompt request");
            Map<String, String> errorResponse = new HashMap<>();
            errorResponse.put("error", "EMPTY_PROMPT");
            return ResponseEntity.badRequest().body(errorResponse);
        }
        
        try {
            String result = deepSeekService.generateCode(prompt);
            
            if (result == null || result.trim().isEmpty()) {
                Map<String, String> errorResponse = new HashMap<>();
                errorResponse.put("error", "SERVICE_ERROR");
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponse);
            }
            
            Map<String, String> response = new HashMap<>();
            response.put("response", result);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            logger.error("Error during code generation", e);
            Map<String, String> errorResponse = new HashMap<>();
            String errorCode = e.getMessage();
            if (!ERROR_CODES.contains(errorCode)) {
                errorCode = "SERVICE_ERROR";
            }
            errorResponse.put("error", errorCode);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponse);
        }
    }
    
    private static final Set<String> ERROR_CODES = Set.of(
        "EMPTY_PROMPT",
        "SERVICE_ERROR",
        "SERVICE_UNAVAILABLE",
        "SERVICE_CONFIG_ERROR"
    );
} 